var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var logger = require('morgan');
const cors = require('cors')


// 解决前端路由与后端路由冲突出错的第三方包
var history = require('connect-history-api-fallback');
// 引入配置反向代理的第三方包
const { createProxyMiddleware } = require('http-proxy-middleware');

// 和vite.config.js中类似配置反向代理
const apiProxy = createProxyMiddleware({
  target: 'http://localhost:3000',
  changeOrigin: true,
  pathRewrite: {'^/api' : ''}
});


var indexRouter = require('./routes/index');
var loginRouter = require('./routes/login');
var logoutRouter = require('./routes/logout');
var logonRouter = require('./routes/admin/logon');
var laboratoryRouter = require('./routes/admin/laboratory');
var equipmentRouter = require('./routes/admin/equipment');
var bookinfoRouter = require('./routes/admin/bookinfo');
var userRouter = require('./routes/admin/user');


var userBookInfoRouter = require('./routes/user/userBookInfo');
var userBookRouter = require('./routes/user/userBook');
var uploadFileRouter = require('./routes/upload');




var app = express();
app.use(history())
app.use('/api', apiProxy);
app.use(cors({
    origin: ['http://localhost:5173'], // 允许的源
    credentials: true // 允许发送凭据（如 cookies）
}));
// 使用session，session存储在cookie中，只要浏览器发起了请求就会检查是否存在session，无论什么类型的请求，如果不存在就会自己创建一个session
// 所以在前端页面刚刚打开时，即使没有点击登录按钮，也会自动创建一个session,这是express-session中间件的特性
app.use(session({
    cookieName: 'session',
    name:'sessionid',
    secret: ' ',//一串随机字符串，用来加密
    cookie: { maxAge: 6000, httpOnly: true },
    //activeDuration: 5 * 60 * 1000,// 激活时间，比如设置为30分钟，那么只要30分钟内用户有服务器的交互，那么就会被重新激活。
  }));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/login', loginRouter);
app.use('/logout', logoutRouter);
app.use('/logon', logonRouter);
app.use('/laboratory', laboratoryRouter);
app.use('/equipment', equipmentRouter);
app.use('/bookinfo', bookinfoRouter);
app.use('/user', userRouter);


app.use('/userBookInfo', userBookInfoRouter);
app.use('/userBook', userBookRouter);
app.use('/upload', uploadFileRouter);




module.exports = app;
